﻿namespace System.Workflow.ComponentModel.Compiler
{
    using Microsoft.Build.Framework;
    using Microsoft.Build.Tasks;
    using Microsoft.Build.Utilities;
    using System;
    using System.Collections.Generic;
    using System.IO;

    internal sealed class CreateWorkflowManifestResourceNameForCSharp : CreateCSharpManifestResourceName
    {
        private bool lastAskedFileWasXoml;
        private List<ITaskItem> resourceFilesWithManifestResourceNames;

        protected override string CreateManifestName(string fileName, string linkFileName, string rootNamespace, string dependentUponFileName, Stream binaryStream)
        {
            string metadataValue = string.Empty;
            if (!this.lastAskedFileWasXoml)
            {
                metadataValue = base.CreateManifestName(fileName, linkFileName, rootNamespace, dependentUponFileName, binaryStream);
            }
            else
            {
                metadataValue = TasksHelper.GetXomlManifestName(fileName, linkFileName, rootNamespace, binaryStream);
            }
            string extension = Path.GetExtension(fileName);
            if ((string.Compare(extension, ".rules", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(extension, ".layout", StringComparison.OrdinalIgnoreCase) == 0))
            {
                metadataValue = metadataValue + extension;
            }
            TaskItem item = new TaskItem(fileName);
            if (!string.IsNullOrEmpty(dependentUponFileName))
            {
                item.SetMetadata("DependentUpon", dependentUponFileName);
            }
            item.SetMetadata("ManifestResourceName", metadataValue);
            if (this.resourceFilesWithManifestResourceNames == null)
            {
                this.resourceFilesWithManifestResourceNames = new List<ITaskItem>();
            }
            this.resourceFilesWithManifestResourceNames.Add(item);
            this.lastAskedFileWasXoml = false;
            return metadataValue;
        }

        protected override bool IsSourceFile(string fileName)
        {
            if (string.Compare(Path.GetExtension(fileName), ".xoml", StringComparison.OrdinalIgnoreCase) == 0)
            {
                this.lastAskedFileWasXoml = true;
                return true;
            }
            return base.IsSourceFile(fileName);
        }

        [Output]
        public ITaskItem[] ResourceFilesWithManifestResourceNames
        {
            get
            {
                return this.resourceFilesWithManifestResourceNames.ToArray();
            }
        }
    }
}

